//
//  GQLoginController.m
//  GuQu
//
//  Created by HELIUM STAR on 15/5/4.
//  Copyright (c) 2015年 HELIUM STAR. All rights reserved.
//

#import "GQLoginController.h"
#import "TipView.h"
#import "GQFogetController.h"
#import "GQRegisterController.h"
#import "Reachability.h"
#import "GQLoginResult.h"
#import "GQLoginParam.h"
#import "GQLoginTool.h"
#import "NSString+Hash.h"
#import "GQLoginUserResult.h"
#import "MBProgressHUD+MJ.h"
#import "GQTabBarController.h"
#import "GQRegisterInfo.h"
#import "UIImageView+WebCache.h"
#import "GQRegisterTool.h"
#import "GQRegisterTagInfo.h"

#define kLoginTextHeight 44
#define kLoginTextMargin 10
#define kLoginViewX 0
#define kLoginViewY 20
#define kSaltString @"HeXingKeJi20159823423443543@@###@#$%)(*###$$###552211&bbbnHeXingKeJi"

@interface GQLoginController () <UITextFieldDelegate>

@property (strong, nonatomic) UIView *loginView;
@property (strong, nonatomic) UIButton *loginBtn;
@property (strong, nonatomic) UIButton *forgetBtn;
@property (strong, nonatomic) UIButton *registerBtn;
@property (strong, nonatomic) UITextField *passwordTextField;
@property (strong, nonatomic) UITextField *accountTextField;
@property (strong, nonatomic) UIView *tipView;
@property (strong, nonatomic) UIView *coverView;

@end

@implementation GQLoginController


- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.frame = CGRectMake(0, kNavigatationBarHeight, kScreenWidth, kScreenHeight - kNavigatationBarHeight);
    self.view.backgroundColor = [UIColor colorWithRed:236 / 255.0 green:236 / 255.0 blue:236 / 255.0 alpha:1.0];
    self.title = @"登录";
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithImage:[UIImage imageWithOriginalName:@"distribute_back"] style:UIBarButtonItemStylePlain target:self action:@selector(backToPre)];
    [self setUpLoginView];
    [self setUpLoginBtn];
    [self setUpPwdAndRegister];
    //[self setUpThirdLogin];
    
    NSLog(@"开启www.baidu.com的网络监测");
    Reachability *reach = [Reachability reachabilityWithHostName:@"www.baidu.com"];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(reachabilityChanged:) name:kReachabilityChangedNotification object:nil];
    [reach startNotifier];
}

- (void)reachabilityChanged:(NSNotification *)noti
{
    Reachability *reach = [noti object];
    if (![reach isReachable]) {
        NSLog(@"网络不可用");
        return;
    }
    NSLog(@"网络可用");
    if (reach.isReachableViaWiFi) {
        NSLog(@"当前通过wifi连接");
        return;
    }else{
        NSLog(@"wifi未开启");
    }
    
    if (reach.isReachableViaWWAN) {
        NSLog(@"当前通过2g或者3g连接");
        return;
    }else{
        NSLog(@"2g 或者 3g不可用");
    }
}

- (void)backToPre
{
    [self.navigationController popViewControllerAnimated:YES];
}

- (void)setUpLoginView
{
    //账户输入框
    UIView *view = [[UIView alloc] initWithFrame:CGRectMake(kLoginViewX, kLoginViewY + kNavigatationBarHeight, kScreenWidth, 90)];
    //左边手机的附属物
    
    UIImageView *phoneImage =[[UIImageView alloc] initWithImage:[UIImage imageWithOriginalName:@"login_mobile"]];
    phoneImage.frame  =CGRectMake(kLoginTextMargin, 4.5, 35, 35);
    [view addSubview:phoneImage];
    
    UITextField *accountTextField = [[UITextField alloc] initWithFrame:CGRectMake(kLoginTextMargin + phoneImage.width, 0, kScreenWidth - kLoginTextMargin * 2 - phoneImage.width, kLoginTextHeight)];
    accountTextField.backgroundColor = [UIColor whiteColor];
    accountTextField.clearButtonMode = UITextFieldViewModeWhileEditing;
    accountTextField.placeholder = @"手机号码";
    accountTextField.keyboardType = UIKeyboardTypeNumbersAndPunctuation;
    accountTextField.delegate = self;
    self.accountTextField = accountTextField;
    view.backgroundColor = [UIColor whiteColor];
    
    UIView *lineView = [[UIView alloc] initWithFrame:CGRectMake(kLoginTextMargin, 45, (kScreenWidth - kLoginTextMargin * 2), 1)];
    lineView.backgroundColor = [UIColor lightGrayColor];
    [view addSubview:lineView];
    
    //密码输入框
    UIImageView *lockImage =[[UIImageView alloc] initWithImage:[UIImage imageWithOriginalName:@"login_lock"]];
    lockImage.frame  =CGRectMake(kLoginTextMargin, 50.5, 35, 35);
    [view addSubview:lockImage];
    
    
    UITextField *passwordTextField = [[UITextField alloc] initWithFrame:CGRectMake(kLoginTextMargin + lockImage.width, 46, kScreenWidth - kLoginTextMargin * 2 - lockImage.width, kLoginTextHeight)];
    passwordTextField.backgroundColor = [UIColor whiteColor];
    
    //附属物
    UIButton *btnAccessEye = [[UIButton alloc] init];
    btnAccessEye.width = 20;
    btnAccessEye.height = 20;
    btnAccessEye.x = kScreenWidth - kLoginTextMargin - btnAccessEye.width;
    btnAccessEye.y = passwordTextField.center.y - btnAccessEye.width / 2;
    btnAccessEye.backgroundColor = [UIColor greenColor];
    //[btnAccessEye addTarget:self action:@selector(BtnAccessEyeDownClick) forControlEvents:UIControlEventTouchDown];
    
    //密码框
    passwordTextField.placeholder = @"密码";
    passwordTextField.secureTextEntry = YES;
    passwordTextField.delegate = self;
    passwordTextField.keyboardType = UIKeyboardTypeNumbersAndPunctuation;
    self.passwordTextField = passwordTextField;
    [view addSubview:accountTextField];
    [view addSubview:passwordTextField];
    [view addSubview:btnAccessEye];
    [self.view addSubview:view];
    self.loginView = view;
    
//    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(phoneNumTextFieldDidChange) name:UITextFieldTextDidChangeNotification object:self.accountTextField];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(passwordTextFieldEndEditing:) name:UITextFieldTextDidChangeNotification object:self.passwordTextField];
}

- (void)passwordTextFieldEndEditing:(NSNotification *)noti
{
    if (self.accountTextField.text.length == 11 && self.passwordTextField.text.length > 5) {
        self.loginBtn.enabled = YES;
        self.loginBtn.backgroundColor = kLoginBtnColor;
    }else{
        self.loginBtn.enabled = NO;
        self.loginBtn.backgroundColor = [UIColor colorWithRed:138/255.0 green:148/255.0 blue:158/255.0 alpha:1.0];
    }
}

- (void)dealloc
{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

#pragma mark - 创建登陆按钮
- (void)setUpLoginBtn
{
    UIButton *btn = [[UIButton alloc] initWithFrame:CGRectMake(kLoginTextMargin, CGRectGetMaxY(self.loginView.frame) + kLoginViewY, (kScreenWidth - kLoginTextMargin * 2), 44)];
    [btn setBackgroundColor:[UIColor colorWithRed:138/255.0 green:148/255.0 blue:158/255.0 alpha:1.0]];
    [btn setTitle:@"登录" forState:UIControlStateNormal];
    [btn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    btn.enabled = NO;
    btn.titleLabel.font = [UIFont systemFontOfSize:14];
    btn.layer.masksToBounds = YES;
    btn.layer.cornerRadius = 5;
    [btn addTarget:self action:@selector(loginBtnClick) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:btn];
    self.loginBtn = btn;
}


#pragma mark - 登陆按钮点击事件
- (void)loginBtnClick
{
    //验证用户名的手机
    self.loginBtn.enabled = NO;
    NSLog(@"123");
    
    NSString *regex1 = @"^1+[3578]+\\d{9}";
    NSPredicate *pred1 = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", regex1];
    BOOL isMatch1 = [pred1 evaluateWithObject:self.accountTextField.text];
    if (!isMatch1) {
        [TipView showToView:self.view tipImage:[UIImage imageNamed:@"login_sad"] tipText:@"手机号码不正确"];
        return;
    }
    
    NSString *regex2 = @"^[a-zA-Z0-9]{6,15}+$";
    NSPredicate *pred2 = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", regex2];
    BOOL isMatch2 = [pred2 evaluateWithObject:self.passwordTextField.text];
    if (!isMatch2) {
        [TipView showToView:self.view tipImage:[UIImage imageNamed:@"login_sad"] tipText:@"用户名格式不正确"];
        return;
    }
    
    //[self.pwdNumber.text stringByAppendingString:kSaltString];
    //[GQRegisterRegParam sharedGQRegisterRegParam].pass = [saltStr hmacMD5StringWithKey:@"hexingkeji"];
    GQLoginParam *param = [[GQLoginParam alloc] init];
    param.account = [self.accountTextField.text stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    NSString *text = [self.passwordTextField.text stringByAppendingString:kSaltString];
    param.pass = [text hmacMD5StringWithKey:@"hexingkeji"];
    
    [GQLoginTool loginWithParam:param success:^(GQLoginResult *result) {
        self.loginBtn.enabled  = YES;
        if ([result.errorCode isEqualToString:@"2005"]) {
            [TipView showToView:self.view tipImage:[UIImage imageNamed:@"login_sad"] tipText:result.message];
            return;
        }else if ([result.errorCode isEqualToString:@"2004"]){
            [TipView showToView:self.view tipImage:[UIImage imageNamed:@"login_sad"] tipText:result.message];
            return;
        }else if(![result.errorCode integerValue]){
            
            GQRegisterInfo *GQRI = [GQRegisterInfo sharedGQRegisterInfo];
            GQLoginUserResult *GQLUR = [GQLoginResult sharedGQLoginResult].user;
//            NSLog(@"777 --- %@", GQLUR.imageB);
            GQRI.icon = [UIImage imageWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:GQLUR.imageB]]];
            GQRI.name = GQLUR.nick;
            GQRI.gender = [GQLUR.sex integerValue] == 1 ? @"男":@"女";
            GQRI.tag = [GQLUR.tagFollow componentsSeparatedByString:@","];
            NSMutableDictionary *tagInfoDict = [NSMutableDictionary dictionary];
            [GQRegisterTool registerLabelInfo:^(NSArray *result) {
                for (GQRegisterTagInfo *tagInfo in result) {
                    [tagInfoDict setObject:tagInfo.name forKey:tagInfo.tagId];
                }
                NSMutableArray *labelText = [NSMutableArray array];
                for (int i = 0; i < GQRI.tag.count; i++) {
                    NSString *index = GQRI.tag[i];
                    [labelText addObject:[tagInfoDict objectForKey:index]];
                }
                
                GQRI.birthday = @"未填写";
                GQRI.location = GQLUR.city;
                GQRI.honour = GQLUR.intro;
                GQRI.label = labelText;
                
                GQTabBarController *GQTBC = [[GQTabBarController alloc] init];
                [self presentViewController:GQTBC animated:NO completion:nil];
            } failure:^(NSError *error) {
                
            }];
           
        }
    } failure:^(NSError *error) {
        
    }];
    
}

- (void)coverViewDidClick
{
    [self.tipView removeFromSuperview];
}

#pragma mark - 忘记密码与注册账号
- (void)setUpPwdAndRegister
{
    NSInteger kWidth = 50;
    NSInteger kHeight = 20;
    
    UIButton *forgetBtn = [[UIButton alloc] initWithFrame:CGRectMake(kLoginTextMargin, CGRectGetMaxY(self.loginBtn.frame) + kLoginTextMargin, kWidth, kHeight)];
    forgetBtn.titleLabel.font = [UIFont systemFontOfSize:12];
    [forgetBtn setTitle:@"忘记密码" forState:UIControlStateNormal];
    [forgetBtn setTitleColor:[UIColor colorWithRed:103 / 255.0 green:103 / 255.0 blue:103 / 255.0 alpha:1.0] forState:UIControlStateNormal];
    [forgetBtn addTarget:self action:@selector(forgetBtnDidClick) forControlEvents:UIControlEventTouchUpInside];
    self.forgetBtn = forgetBtn;
    [self.view addSubview:forgetBtn];
    
    UIButton *registerBtn = [[UIButton alloc] initWithFrame:CGRectMake(kScreenWidth - kLoginTextMargin - kWidth, CGRectGetMaxY(self.loginBtn.frame) + kLoginTextMargin, kWidth, kHeight)];
    registerBtn.titleLabel.font = [UIFont systemFontOfSize:12];
    [registerBtn setTitle:@"注册账号" forState:UIControlStateNormal];
    [registerBtn setTitleColor:[UIColor colorWithRed:103 / 255.0 green:103 / 255.0 blue:103 / 255.0 alpha:1.0] forState:UIControlStateNormal];
    [registerBtn addTarget:self action:@selector(registerBtnClick) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:registerBtn];
    self.registerBtn = registerBtn;
}

#pragma mark - 注册账号
- (void)registerBtnClick
{
    GQRegisterController *GQRC = [[GQRegisterController alloc] init];
    [self.navigationController pushViewController:GQRC animated:YES];
}

#pragma mark - 忘记密码
- (void)forgetBtnDidClick
{
    GQFogetController *GWFC = [[GQFogetController alloc] init];
    [self.navigationController pushViewController:GWFC animated:YES];
}

- (void)setUpThirdLogin
{
    NSInteger labelWidth = 60;
    NSInteger labelHeight = 24;
    CGFloat thirdBtnViewWidth = 200;
    CGFloat thirdBtnViewHeight = 60;
    CGFloat thirdBtnWidth = 40;
    
    UIColor *lineColor = [UIColor lightGrayColor];
    
    UILabel *label = [[UILabel alloc] init];
    //label.backgroundColor = [UIColor redColor];
    label.frame = CGRectMake(kScreenWidth / 2 - labelWidth / 2, CGRectGetMaxY(self.forgetBtn.frame), labelWidth, labelHeight);
    
    label.font = [UIFont systemFontOfSize:12];
    label.text = @"第三方登陆";

    CGFloat lineWidth = (kScreenWidth - 4 * kLoginTextMargin - labelWidth) / 2;
    
    UIView *leftView = [[UIView alloc] initWithFrame:CGRectMake(kLoginTextMargin, label.center.y, lineWidth, 1)];
    leftView.backgroundColor = lineColor;
    
    UIView *rightView = [[UIView alloc] initWithFrame:CGRectMake(CGRectGetMaxX(label.frame) + kLoginTextMargin, label.center.y, lineWidth, 1)];
    rightView.backgroundColor = lineColor;
    
    UIView *thirdBtnView = [[UIView alloc] initWithFrame:CGRectMake(kScreenWidth / 2 - thirdBtnViewWidth / 2, CGRectGetMaxY(label.frame), thirdBtnViewWidth, thirdBtnViewHeight)];
    
    UIButton *QQBtn = [[UIButton alloc] initWithFrame:CGRectMake(thirdBtnWidth / 2, thirdBtnViewHeight / 2, thirdBtnWidth, thirdBtnWidth)];
    QQBtn.backgroundColor = [UIColor redColor];
    [thirdBtnView addSubview:QQBtn];
    
    UIButton *MicroMesBtn = [[UIButton alloc] initWithFrame:CGRectMake(thirdBtnViewWidth / 2 - thirdBtnWidth / 2, thirdBtnViewHeight / 2, thirdBtnWidth, thirdBtnWidth)];
    MicroMesBtn.backgroundColor = [UIColor redColor];
    [thirdBtnView addSubview:MicroMesBtn];
    
    UIButton *WeiBoBtn = [[UIButton alloc] initWithFrame:CGRectMake(thirdBtnViewWidth / 2 +thirdBtnWidth, thirdBtnViewHeight / 2, thirdBtnWidth, thirdBtnWidth)];
    WeiBoBtn.backgroundColor = [UIColor redColor];
    [thirdBtnView addSubview:WeiBoBtn];
    
    [thirdBtnView addSubview:QQBtn];
    
    [self.view addSubview:label];
    [self.view addSubview:leftView];
    [self.view addSubview:rightView];
    [self.view addSubview:thirdBtnView];
    
}

@end
